import {useRef} from 'react';
import {Badge, message} from 'antd';
import type {ProColumns, ActionType} from '@ant-design/pro-table';
import {crud, stopIde, getIdeUrl, startIde} from './api';
import BasicForm, {INGRESS_MAPPING, PORT_MAPPING, VOLUME_MAPPING} from './form';
import BasicFormTable from '@/components/BasicFormTable';
import {handleAction} from '@/utils/handler';
import {formatMappingFromListToStr, formatMappingFromStrToList} from '@/utils/utils';

const INGRESS_KEYS = INGRESS_MAPPING.map((item) => item.name);
const PORT_KEYS = PORT_MAPPING.map((item) => item.name);
const VOLUME_KEYS = VOLUME_MAPPING.map((item) => item.name);
const SEPARATORS = [';', ':'];

export const STATUS = {
  NONE: 0,
  STARTING: 1,
  RUNNING: 2,
  STOPPING: 3,
};

export default () => {
  const tableRef = useRef<ActionType>();

  const onReload = () => {
    tableRef?.current?.reload?.();
  };

  const normalize = (data: AnyFields) => {
    data['ingress_config'] = formatMappingFromListToStr(INGRESS_KEYS, SEPARATORS, data.ingress);
    data['port_config'] = formatMappingFromListToStr(PORT_KEYS, SEPARATORS, data.ports);
    data['volume_config'] = formatMappingFromListToStr(VOLUME_KEYS, SEPARATORS, data.volumes);
    if (data.stack_ids != null) {
      data['stack_ids'] = data.stack_ids.join(',')
    }
    return data
  };

  const columns: ProColumns<IdeEntity>[] = [
    {
      title: '名称',
      dataIndex: 'name',
    },
    {
      title: '镜像源',
      dataIndex: 'ide_registry',
      hideInSearch: true,
    },
    {
      title: '镜像',
      dataIndex: 'ide_image',
      hideInSearch: true,
    },
    {
      title: '资源配置',
      dataIndex: 'ide_environment',
      hideInSearch: true,
    },
    {
      title: '状态',
      dataIndex: 'status',
      hideInSearch: true,
      render: (_, record) =>
        [
          <Badge key="default" status="default" text="关闭"/>,
          <Badge key="starting" status="processing" text="启动中"/>,
          <Badge key="success" status="success" text="运行中"/>,
          <Badge key="stopping" status="processing" text="关闭中"/>,
        ][record.status],
    },
    {
      title: '创建时间',
      key: 'created',
      dataIndex: 'created',
      valueType: 'dateTime',
      hideInSearch: true,
    },
  ];

  return (
    <BasicFormTable<IdeEntity>
      tableRef={tableRef}
      title={'开发环境'}
      columns={columns}
      polling={(data) =>
        data.some((item) => [STATUS.STARTING, STATUS.STOPPING].includes(item.status)) ? 2000 : 0
      }
      postData={(data) =>
        data.map((item) => {
            item['ingress'] = formatMappingFromStrToList(INGRESS_KEYS, SEPARATORS, item.ingress_config);
            item['ports'] = formatMappingFromStrToList(PORT_KEYS, SEPARATORS, item.port_config);
            item['volumes'] = formatMappingFromStrToList(VOLUME_KEYS, SEPARATORS, item.volume_config);
            if (item.ide_stack_id != '') {
              item['stack_ids'] = item.ide_stack_id.split(',');
            }
            return item;
          }
        )
      }
      crud={{
        ...crud,
        add: (data) => crud.add(normalize(data)),
        update: (data) => crud.update(normalize(data)),
      }}
      addForm={<BasicForm/>}
      updateForm={<BasicForm/>}
      renderActions={(actions, record) => {
        if (record.status === 2) {
          return [
            <a
              key="stop"
              onClick={async () => {
                const success = await handleAction(record.id, stopIde, '新增关闭任务');
                if (success) onReload();
              }}
            >
              关闭
            </a>,
            <a
              key="open"
              onClick={async () => {
                try {
                  const ideData = await getIdeUrl(record.id);
                  window.open(ideData.data.url);
                } catch (error) {
                  message.error('获取地址出错');
                }
              }}
            >
              查看
            </a>,
          ];
        }
        if ([1, 3].includes(record.status)) {
          return actions;
        }
        return [
          <a
            key="start"
            onClick={async () => {
              const success = await handleAction(record.id, startIde, '新增启动任务');
              if (success) onReload();
            }}
          >
            启动
          </a>,
        ].concat(actions);
      }}
    />
  );
};
